﻿using Lingmeng.EntityFrameworkCore.core;
using Lingmeng.EntityFrameworkCore.Extensions;
using Microsoft.EntityFrameworkCore;
using Video.Application.Contract.UserInfos.Dtos;
using Video.Domain;
using Video.Domain.UserRepository;
using Video.Domain.Users;

namespace Video.EntityFrameworkCore.Users
{
    public class UserInfoRepository : Repository<VideoDbContext, UserInfo>, IUserInfoRepository
    {
        public UserInfoRepository(VideoDbContext dbContetx) : base(dbContetx)
        {
        }

        public async Task<UserInfoRoleView?> GetAsync(Guid guid)
        {
            var userinfo = await _dbContext.UserInfo.Where(x => x.Id == guid)
                .Select(x => new UserInfoRoleView()
                {
                    Avatar = x.Avatar,
                    CreatedTime = x.CreatedTime,
                    Enable = x.Enable,
                    Id = x.Id,
                    Name = x.Name,
                    Password = x.Password,
                    UserName = x.UserName,
                }).FirstOrDefaultAsync();
            if (userinfo == null)
            {
                return null;
            }
            //查询Role表是否跟UserRole表是否存在关联，存在关联则返回Role表数据
            var query =
                from role in _dbContext.Role
                join userRole in _dbContext.UserRole on role.Id equals userRole.RoleId
                where userRole.UserId == userinfo.Id
                select role;
            userinfo.Role = await query.ToListAsync();
            return userinfo;
        }

        public async Task<Role> GetAsync(string cold)
        {
            var role = await _dbContext.Role.FirstOrDefaultAsync(x => x.Code == cold);
            return role;

        }

        public async Task<UserInfoRoleView?> GetUserInfoRoleAsync(string username, string password)
        {
            var userinfo = await _dbContext.UserInfo.Where(x => x.UserName == username && x.Password == password)
                .Select(x => new UserInfoRoleView()
                {
                    Avatar = x.Avatar,
                    CreatedTime = x.CreatedTime,
                    Enable = x.Enable,
                    Id = x.Id,
                    Name = x.Name,
                    Password = x.Password,
                    UserName = x.UserName,
                }).FirstOrDefaultAsync();
            if (userinfo == null)
            {
                return null;
            }
            //查询Role表是否跟UserRole表是否存在关联，存在关联则返回Role表数据
            var query =
                from role in _dbContext.Role
                join userRole in _dbContext.UserRole on role.Id equals userRole.RoleId
                where userRole.UserId==userinfo.Id
                select role;
            userinfo.Role = await query.ToListAsync();
            return userinfo;
        }
        //查询用户信息并返回分页列表
        public async Task<List<UserInfo>> GetListAsync(string? keywords, DateTime? startTime, DateTime? endTime, int skipCount, int maxResultCount)
        {
            var query = CreateQueryable(keywords, startTime, endTime);
            return await query.PageBy(skipCount, maxResultCount).ToListAsync();
        }
        //查询用户总数
        public async Task<int> GetCountAsync(string? keywords, DateTime? startTime, DateTime? endTime)
        {
            var query = CreateQueryable(keywords, startTime, endTime);
            return await query.CountAsync();
        }
        
        //根据关键字，创建时间等条件进行筛选 且x.Nmae与x.UserName均不能为空
        private IQueryable<UserInfo> CreateQueryable(string? keywords, DateTime? startTime, DateTime? endTime)
        {
            var query =
                _dbContext.UserInfo.WhereIf(!string.IsNullOrEmpty(keywords),
                    x => EF.Functions.Like(x.Name, keywords!) && EF.Functions.Like(x.UserName, keywords!))
                    .WhereIf(startTime.HasValue, x => x.CreatedTime >= startTime)
                    .WhereIf(endTime.HasValue, x => x.CreatedTime <= endTime);

            return query;
        }

        public async Task DeleteAsync(IEnumerable<Guid> guid)
        {
            var value=await FindGuidAsync(guid);
            if(value!=null&&value.Count>0)
            {
                var valueToDelete =await _dbContext.UserInfo.Where(x =>value.Contains(x.Id)).ToListAsync();
                _dbContext.RemoveRange(valueToDelete);
                await _dbContext.SaveChangesAsync();
            }
            //await _dbContext.Database.ExecuteSqlRawAsync("SELECTE FROM UserInfos Where Id IN({0})",string.Join(",", guid));
        }
        private async Task<List<Guid>> FindGuidAsync(IEnumerable<Guid> guids)
        {
            return await _dbContext.UserInfo.Where(x => guids.Contains(x.Id)).Select(x => x.Id).ToListAsync();
        }

        public async Task EnableAsync(IEnumerable<Guid> guid,bool enable=true)
        {
            //string.Join(",", guid)的意思是将数组中的guid转换为用逗号隔开的字符串格式
            await _dbContext.Database.ExecuteSqlRawAsync("UPDATE UserInfos Set Enable=false WHERE Id IN({0})", string.Join(",", guid));
        }

        
    }
}
